﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Peekaboo2008.dao;
using Peekaboo2008.common;
using Peekaboo2008.model;
using Peekaboo2008.controls;
using System.Collections;

namespace Peekaboo2008.view
{
    public partial class FormXuatTraNhaCungCap : Form
    {
        System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle = new System.Windows.Forms.DataGridViewCellStyle();
        DataTable tbKhoHang;
        DataTable tbDanhSachHangHoa = new DataTable();
        DataGridViewMultiColumnComboColumn newColumn;

        //Luu id cua phieu nhap xuat da insert
        private String outPhieuNhapXuatId = "";

        //Kich hoat khi ng dung da luu hoa don thanh cong
        private Boolean IsSaved = false;

        private String MaHoaDon = "";
        private double TiGia = 0;
        private double CongTienHang = 0;
        private double TienVAT = 0;
        private double ChietKhau = 0;
        private double ChietKhauVND = 0;
        private double TongTien = 0;
        private double ThanhToan = 0;
        private double ThanhToanVND = 0;
        private double ConNo = 0;
        private double ConNoVND = 0;

        public FormXuatTraNhaCungCap()
        {
            InitializeComponent();
            initNgayNhapHoaDon();
            initNhanVien();
            initLoaiTien();
            initHangHoaTrongKho();
            initHinhThucThanhToan();
            initDanhSachNhaCungCap();
            initMaHoaDon();
            initMultiColumn();
            enableForm(false);
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        /*Khoi tạo txt ngay nhap hoa don*/
        private void initNgayNhapHoaDon()
        {
            txtNgayTaoHoaDon.Text = CommonDAO.getDate();
        }
        /*Khoi tạo loai tien thanh toan*/
        private void initLoaiTien()
        {
            cbxLoaiTien.Items.Add("VND");
            cbxLoaiTien.Items.Add("USD");
            cbxLoaiTien.SelectedIndex = 0;
        }
        /*Khoi tạo hinh thuc thanh toan*/
        private void initHinhThucThanhToan()
        {
            DataTable tb = HinhThucThanhToanDAO.getAll();
            cbxHinhThucThanhToan.DataSource = HinhThucThanhToanDAO.getAll();
            cbxHinhThucThanhToan.DisplayMember = "Ten";
            cbxHinhThucThanhToan.ValueMember = "ID";
        }

        /*lay ma khu vuc cua nhan vien hien hanh
        *khi nao moi nguoi chinh sua xong kieu du lieu sai lech trong model thi bo PARSE
        */
        private ChiNhanhModel getKhuVuc()
        {
            return ChiNhanhDAO.getByMaChiNhanh(Constants.USER_LOGIN.MaChiNhanh);
        }

        /*Khoi tao danh sach nha cung cap
         * 
         */
        private void initDanhSachNhaCungCap(){
            cbxNhaCungCap.DataSource = KhachHangDAO.NhaCungCap_GetAll();
            cbxNhaCungCap.DisplayMember = "Ten";
            cbxNhaCungCap.ValueMember = "ID";
        }

        private void enableForm(Boolean _vl)
        {
            if (!_vl)
            {
                grbSanPham.Enabled = false;
                grbThongKeTien.Enabled = false;

                enableLuuHoaDon();
                enableHuyInXemInHoaDon();
            }
            else
            {
                grbSanPham.Enabled = true;
                grbThongKeTien.Enabled = true;

                enableLuuHoaDon();
                enableHuyInXemInHoaDon();
            }
        }
        /**/
        private void initMaHoaDon()
        {
            String[] _s = CommonDAO.getDate().Split('-');
            MaHoaDon = "HDX-T" + _s[2] + _s[1] + _s[0] + "-*****";
            txtMaHoaDon.Text = MaHoaDon.ToString();
        }

        /*Load nhan nhien dang dang nhap vao cbxNhanVien*/
        private void initNhanVien()
        {
            DataTable dt = ThanhVienDAO.GetAllThanhVien();
            cbxNhanVien.DataSource = ThanhVienDAO.GetAllThanhVien();
            cbxNhanVien.DisplayMember = "HoTen";
            cbxNhanVien.ValueMember = "MaThanhVien";
            cbxNhanVien.SelectedItem = Constants.USER_LOGIN.MaThanhVien;
        }
        /*Lay du lieu tat ca hang hoa trong kho hang*/
        private void initHangHoaTrongKho()
        {
            tbKhoHang = HangHoaDAO.getHangHoaTonKhoOfChiNhanhByMaChiNhanh(Constants.USER_LOGIN.MaChiNhanh);
        }
        private void initMultiColumn()
        {
            int position = 1;

            newColumn = new DataGridViewMultiColumnComboColumn();

            newColumn.CellTemplate = new DataGridViewMultiColumnComboCell();
            newColumn.DataSource = tbKhoHang;
            newColumn.HeaderText = "Tên hàng";
            newColumn.Name = "clmMaTenHangHoa";
            newColumn.DisplayMember = tbKhoHang.Columns["Ten_hang_hoa"].ColumnName;
            newColumn.ValueMember = tbKhoHang.Columns["Ma_hang_hoa"].ColumnName;
            newColumn.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            dataGridViewCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            newColumn.DefaultCellStyle = dataGridViewCellStyle;
            grvDanhSachHangHoa.Columns.Insert(position, newColumn);
            grvDanhSachHangHoa.Columns[position].Width = 300;
        }

        private void btnThemNhanh_Click(object sender, EventArgs e)
        {
            //FormXuatTraNhaCungCap formXuatTraNCC = new FormXuatTraNhaCungCap();
            //formXuatTraNCC = this;
            //this.Enabled = false;
            //FormNhaCungCap formNhaCC = new FormNhaCungCap(ref formXuatTraNCC);
            //formNhaCC.ShowDialog();
        }

        private void txtCongTienHang_TextChanged(object sender, EventArgs e)
        {
            ChietKhauVND = ChietKhau * CongTienHang / 100;
            txtChietKhauVND.Text = formatToNumber(ChietKhauVND) + "đ";
            TongTien = CongTienHang - TienVAT + ChietKhauVND;
            txtTongTien.Text = formatToNumber(TongTien) + "đ";
            enableLuuHoaDon();
        }


        /*Format du lieu double neu nhu no lon hon 0 thi giu nguyen con khong thi them dau tru
         ngoai ra format giu nguyen truong cua gia tri, miền giá trị không bị rút gọn giống như 21E+23
         */
        private String formatToNumber(double _vl)
        {
            String _rs = "";
            _rs = _vl >= 0 ? String.Format("{0:0.##}", _vl) : ("-" + String.Format("{0:0.#}", _vl));
            return _rs;
        }

        private void txtTiGia_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtTiGia_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == (Keys.Control | Keys.V))
                txtTiGiaVND.Text = "0";
            if (!String.IsNullOrEmpty(txtTiGiaVND.Text.Trim()) && !txtTiGiaVND.Text.Trim().Equals(""))
            {
                TiGia = double.Parse(txtTiGiaVND.Text.Trim());
                kiemTraThanhToan();
            }
        }

        private void grvDanhSachHangHoa_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == grvDanhSachHangHoa.Columns["clmSoLuong"].Index &&
                    grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmSoLuong"].Value != null &&
                    grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmMaTenHangHoa"].Value != null)
            {
                //Kiem tra neu nhu so nhap vao khong la chu so hoat rong thi chuyen thanh 0
                String _validSoLuongVal = grvDanhSachHangHoa.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = isNumber(_validSoLuongVal, 0, int.MinValue, int.MaxValue).ToString();

                String _itemID = grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmMaHangHoa"].Value.ToString();
                String _donGia = grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmDonGia"].Value.ToString();
                String _soLuong = grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmSoLuong"].Value.ToString();
                _soLuong = String.IsNullOrEmpty(_soLuong) ? "0" : _soLuong;

                String _vat = grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmVAT"].Value.ToString();
                String _ck = grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmPCK"].Value.ToString();
                try
                {
                    grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmThanhTien"].Value = (double.Parse(_donGia) * double.Parse(_soLuong)).ToString();
                    grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmTienVAT"].Value = (double.Parse(_donGia) * double.Parse(_soLuong) * (double.Parse(_vat) / 100)).ToString();
                    grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmTienCK"].Value = (double.Parse(_donGia) * double.Parse(_soLuong) * (double.Parse(_ck) / 100)).ToString();
                    getTongTien();
                    kiemTraThanhToan();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace.ToString());
                }
            }
            else if (e.ColumnIndex == grvDanhSachHangHoa.Columns["clmMaTenHangHoa"].Index &&
                        grvDanhSachHangHoa.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
            {
                String _id = grvDanhSachHangHoa.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                DataTable _tbResult = HangHoaDAO.getHangHoaTonKhoOfChiNhanhByMaChiNhanh_MaHang(Constants.USER_LOGIN.MaChiNhanh, _id);
                grvDanhSachHangHoa.Columns["clmMaTenHangHoa"].DisplayIndex = 0;

                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmMaHangHoa"].Value = _tbResult.Rows[0]["Ma_hang_hoa"].ToString();
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmTenHangHoa"].Value = _tbResult.Rows[0]["Ten_hang_hoa"].ToString();
                String _MaDonViQuiDoi = _tbResult.Rows[0]["Ma_don_vi_qui_doi"].ToString();
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmDonViTinh"].Value = _MaDonViQuiDoi;
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmTenDonViTinh"].Value =
                                                        DonViQuiDoiDAO.GetByID(_MaDonViQuiDoi).DonViGoc;
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmDonGia"].Value = _tbResult.Rows[0]["Gia_nhap_cuoi"].ToString();
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmSoLuong"].Value = "0";
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmSoLuongTon"].Value = _tbResult.Rows[0]["So_luong_ton"].ToString();
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmThanhTien"].Value = "0";
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmVAT"].Value = _tbResult.Rows[0]["VAT"].ToString();
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmTienVAT"].Value = "0";
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmPCK"].Value = "0";
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmTienCK"].Value = "0";
                grvDanhSachHangHoa.Rows[e.RowIndex].Cells["clmGhiChu"].Value = "";

            }
        }
        /**
         * Kiem tra du lieu dua vao co phai la kieu int va nam trong gioi han cua int hay ko
         * */
        private int isNumber(Object _Input, int _DefaultVal, int _MinVal, int _MaxVal)
        {
            int _Val = _DefaultVal;
            if (!String.IsNullOrEmpty(_Input.ToString()))
            {
                try
                {
                    _Val = int.Parse(_Input.ToString());
                    if (_Val > _MaxVal || _Val < _MinVal)
                    {
                        _Val = _DefaultVal;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    _Val = _DefaultVal;
                }
            }
            else
            {
                _Val = _DefaultVal;
            }
            return _Val;
        }
        /*Tong tien dong hang trong list danh sach hang mua*/
        private void getTongTien()
        {
            CongTienHang = 0;
            TienVAT = 0;
            foreach (DataGridViewRow dr in grvDanhSachHangHoa.Rows)
            {
                if (dr.Cells["clmSoLuong"].Value != null && !dr.Cells["clmSoLuong"].Value.ToString().Equals("0") &&
                    !dr.Cells["clmSoLuong"].Value.ToString().Equals(""))
                {
                    CongTienHang += double.Parse(dr.Cells["clmThanhTien"].Value.ToString());
                    TienVAT += double.Parse(dr.Cells["clmTienVAT"].Value.ToString());
                }
            }

            txtCongTienHang.Text = formatToNumber(CongTienHang) + "đ";
            txtTienVAT.Text = formatToNumber(TienVAT) + "đ";
        }

        /*Kiem tra tien khach hang thanh toan va tra ve so tien van tra
         hoac so tien phai thoi lai cho khach hang
         */
        private void kiemTraThanhToan()
        {
            ThanhToan = String.IsNullOrEmpty(txtThanhToan.Text.Trim()) ? 0 : double.Parse(txtThanhToan.Text.Trim());

            ThanhToanVND = cbxLoaiTien.SelectedItem.Equals("USD") ? (TiGia * ThanhToan) : ThanhToan;
            if (checkInfNaN(ThanhToanVND))
            {
                MessageBox.Show(this, "Số tiền thanh toán quá lớn\n" +
                        "Vui lòng kiểm tra lại tỉ giá hoặc số tiền khách trả");
                ThanhToan = 0;
                txtThanhToan.Text = ThanhToan.ToString();

                TiGia = 0;
                txtTiGiaVND.Text = TiGia.ToString();
            }
            else
            {
                ConNoVND = ThanhToanVND - TongTien;
                TiGia = TiGia != 0 ? TiGia : 1;
                ConNo = cbxLoaiTien.SelectedItem.Equals("USD") ? (ConNoVND / TiGia) : ConNoVND;
                txtThanhToanVND.Text = formatToNumber(ThanhToanVND) + "đ";
                txtConNoVND.Text = ConNoVND.ToString() + "đ";
                txtConNo.Text = ConNo + moneyPrefix();
                enableLuuHoaDon();
            }
        }

        /*Kiem tra gia tri double co vuot qua gioi han chua cua kieu du lieu hay khong
         neu co thi bao loi nguoi dung
         */
        private bool checkInfNaN(double _value)
        {
            bool _rs = false;
            if (_value == double.MaxValue || _value == double.NaN)
            {
                _rs = true;
            }
            return _rs;
        }

        /*Hau to don vi tien te*/
        private String moneyPrefix()
        {
            String _rs = cbxLoaiTien.SelectedItem.Equals("USD") ? "$" : "đ";
            return _rs;
        }
        private void fullInsert()
        {
            Boolean _rs = true;
            PhieuNhapXuatModel phieuNhap = new PhieuNhapXuatModel();
            phieuNhap.KyHieu = txtMaHoaDon.Text;
            phieuNhap.GhiChu = "";
            phieuNhap.MaKhachHangNhaCungCap = cbxNhaCungCap.SelectedValue.ToString();
            phieuNhap.MaNhanVien = cbxNhanVien.SelectedValue.ToString();
            phieuNhap.TongTien = CongTienHang.ToString();
            phieuNhap.TienThue = TienVAT.ToString();
            phieuNhap.ThanhTien = TongTien.ToString();
            phieuNhap.ThanhToan = ThanhToan.ToString();
            phieuNhap.ChietKhau = ChietKhau.ToString();
            phieuNhap.TienChietKhau = ChietKhauVND.ToString();
            phieuNhap.TyGia = TiGia.ToString();
            phieuNhap.TienNo = ConNoVND.ToString();
            phieuNhap.MaHinhThucThanhToan = cbxHinhThucThanhToan.SelectedValue.ToString();

            outPhieuNhapXuatId = PhieuNhapXuatDAO.InsertTraHangNCC(phieuNhap);
            if (!outPhieuNhapXuatId.Equals(""))
            {
                String outId = "";
                ChiTietNhapXuatModel _model;
                grvDanhSachHangHoa.AllowUserToAddRows = false;
                foreach (DataGridViewRow _dgr in grvDanhSachHangHoa.Rows)
                {
                    _model = new ChiTietNhapXuatModel();
                    _model.MaPhieuNhapXuat = outPhieuNhapXuatId;
                    _model.MaHangHoa = _dgr.Cells["clmMaHangHoa"].Value.ToString();
                    _model.GhiChu = _dgr.Cells["clmGhiChu"].Value.ToString();
                    _model.SoLuong = _dgr.Cells["clmSoLuong"].Value.ToString();
                    _model.GiaBan = _dgr.Cells["clmDonGia"].Value.ToString();
                    _model.ThanhTien = _dgr.Cells["clmThanhTien"].Value.ToString();
                    _model.Thue = _dgr.Cells["clmVAT"].Value.ToString();
                    _model.TienThue = _dgr.Cells["clmTienVAT"].Value.ToString();
                    _model.TongTien = (float.Parse(_dgr.Cells["clmThanhTien"].Value.ToString()) - 
                        float.Parse(_dgr.Cells["clmThanhTien"].Value.ToString()) * float.Parse(_dgr.Cells["clmVAT"].Value.ToString()) / 100).ToString();
                    _model.ChietKhau = _dgr.Cells["clmPCK"].Value.ToString();
                    _model.TienChietKhau = _dgr.Cells["clmTienCK"].Value.ToString();
                    _model.HanSuDung = "";
                    _model.BaoHanh = "";
                    _model.PhiVanChuyen = "0";
                    _model.SoLuongGoc = _dgr.Cells["clmSoLuongTon"].Value.ToString();

                    outId = ChiTietNhapXuatDAO.Insert(_model);
                    if (outId.Equals(""))
                    {
                        //Co loi~ revert lai
                        //Xoa tat ca cac ban ghi lien quan den ma phieu nhap xuat trong chi tiet nhap xuat va bang phieu xuat nhap
                        //Thong bao loi~ den nguoi dung
                        _rs = false;
                        ChiTietNhapXuatDAO.deleteByMaPhieuNhapXuat(outPhieuNhapXuatId);
                        PhieuNhapXuatDAO.deleteById(outPhieuNhapXuatId);
                        break;
                    }
                    else
                    {
                        HangTonDAO.updateSoLuongTonKhoOfTraHangByMaChiNhanh_MaHang(Constants.USER_LOGIN.MaChiNhanh, _model.MaHangHoa, _model.SoLuong);
                    }
                }
            }
            else
            {
                //neu cap nhap phieu bi loi thi chuyen trang thai result thanh false ~ that bai
                _rs = false;
            }
            //Neu qua trinh cap nhap thanh con, reset lai cac truong gia tri cua form, va bien
            //con khong bao loi
            if (_rs)
            {
                clearForm();
                IsSaved = true;
                enableLuuHoaDon();
                enableHuyInXemInHoaDon();
                enableForm(false);
            }
            else
            {
                MessageBox.Show(this, "Có lỗi xẩy ra trong quá trình cập nhập dữ liệu,\nXem xét lại đường truyền hoặc restart máy tính", "Lỗi", MessageBoxButtons.OK);
            }
        }
        private void clearForm()
        {
            TiGia = 0;
            CongTienHang = 0;
            TienVAT = 0;
            ChietKhau = 0;
            ChietKhauVND = 0;
            TongTien = 0;
            ThanhToan = 0;
            ThanhToanVND = 0;
            ConNo = 0;
            ConNoVND = 0;

            initMaHoaDon();
            initNhanVien();
            initNgayNhapHoaDon();
            initLoaiTien();
            initHinhThucThanhToan();
            initDanhSachNhaCungCap();
            grvDanhSachHangHoa.Rows.Clear();
            grvDanhSachHangHoa.AllowUserToAddRows = true;

            txtCongTienHang.Text = "0";
            txtTienVAT.Text = "0đ";
            txtChietKhau.Text = "0%";
            txtChietKhauVND.Text = "0đ";
            txtTongTien.Text = "0đ";
            txtThanhToan.Text = "";
            txtThanhToanVND.Clear();
            txtConNo.Clear();
            txtConNoVND.Clear();
        }

        private void enableLuuHoaDon()
        {
            btnLuuHoaDon.Enabled = TongTien > 0 ? true : false;
        }

        private void enableHuyInXemInHoaDon()
        {
            btnHuyHoaDon.Enabled = IsSaved ? true : false;
            btnInHoaDon.Enabled = IsSaved ? true : false;
            btnXemIn.Enabled = IsSaved ? true : false;
        }

        private void btnLuuHoaDon_Click(object sender, EventArgs e)
        {
            if (ConNoVND < 0)
            {
                DialogResult anw = MessageBox.Show(this, "Thanh toán còn thiếu: " + ConNoVND.ToString() + "đ", "Cảnh báo", MessageBoxButtons.YesNo);
                if (anw == DialogResult.Yes)
                {
                    fullInsert();
                }
            }
            else
            {
                fullInsert();
            }
        }

        private void btnHuyHoaDon_Click(object sender, EventArgs e)
        {
            DialogResult rs = MessageBox.Show(this, "Bạn muốn hủy hóa đơn?", "Thông báo", MessageBoxButtons.YesNo);
            if (rs == DialogResult.Yes && !String.IsNullOrEmpty(outPhieuNhapXuatId))
            {
                //Neu nhu ng dung nhap OK va outPhieuNhapXuatId khac rong thi se xoa trong 2 bang
                ChiTietNhapXuatDAO.deleteByMaPhieuNhapXuat(outPhieuNhapXuatId);
                PhieuNhapXuatDAO.deleteById(outPhieuNhapXuatId);

                //Doi lai gia tri cua cac truong lien quan
                outPhieuNhapXuatId = "";
                IsSaved = false;
                enableHuyInXemInHoaDon();
                enableLuuHoaDon();
            }
        }

        private void btnInHoaDon_Click(object sender, EventArgs e)
        {
            //Thao tac in, khong the cho huy bang ghi nua
            IsSaved = false;
            enableHuyInXemInHoaDon();
        }

        private void btnXemIn_Click(object sender, EventArgs e)
        {

        }

        private void btnTimKiem_Click(object sender, EventArgs e)
        {

        }

        private void cbxLoaiTien_SelectedIndexChanged(object sender, EventArgs e)
        {
            kiemTraThanhToan();
        }

        private void txtThanhToan_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtThanhToan_KeyUp(object sender, KeyEventArgs e)
        {
            kiemTraThanhToan();
        }

        private void tsbTaoHoaDonXuat_Click(object sender, EventArgs e)
        {
            enableForm(true);
        }
    }
}
